#
#
# http://codekata.pragprog.com/2007/01/kata_two_karate.html
#
# Alberto Massa
# 12th of April, 2010
#
#
# un'oraemmezza
#  errori:
#   sbagliato la base di fine ricorsione
#   assegnamenti sbagliati
#   infiniti errori della cortocircuitazione degli if
#
#

import unittest

def monadic_equals(x, y):
	return x==y
def monadic_compare(x, y):
	return x>y 

def chop(n, inarray, inlength):
	print()
	arraylength = len(inarray)-1
	l = 0
	r = arraylength
	#return not inarray and -1 or int(recursive_chop1(n, inarray, l, r))
	return not inarray and -1 or int(recursive_chop2(n, inarray))

def recursive_chop1(n, inarray, l, r):
	#--------------------------------------------------- Dicotomic search	
	index = (l+r)//2
	x = inarray[index]	

	# hack: cast to string cause if right result is 0 and-or short-circuiting fails
	return monadic_compare(l, r) and -1 or  \
		monadic_equals(x,n) and str(index) or \
		 recursive_chop1(n, inarray, 
				(monadic_compare(n,x) and index+1 or l ), 
				(monadic_compare(n,x) and r or index-1 ))

#def recursive_chop2(n, inarray, i):
#	index = len(inarray)//2
#	print("1-",index, inarray)
#	x = inarray[index]
#	print("2-",n, x, index, inarray)
#	# hack: cast to string cause if right result is 0 and-or short-circuiting fails
#	return monadic_equals(x,n) and str(index) or \
#		(monadic_compare(0, len(inarray)) or len(inarray)==1) and -1 or  \
#		 recursive_chop2(n, monadic_compare(n,x) and inarray[index:] or inarray[:-index], i)

class Test(unittest.TestCase):
	def test(self):
		#--------------------------------------------------- test
		self.assertEqual(-1, chop( 3, [], 0 ));
		self.assertEqual(-1, chop( 3, [1], 1 ));
		self.assertEqual(0,  chop( 1, [1], 1 ));

		self.assertEqual(0,  chop(1, [1, 3, 5], 3));
		self.assertEqual(1,  chop(3, [1, 3, 5], 3));
		self.assertEqual(2,  chop(5, [1, 3, 5], 3));
		self.assertEqual(-1, chop(0, [1, 3, 5], 3));
		self.assertEqual(-1, chop(2, [1, 3, 5], 3));
		self.assertEqual(-1, chop(4, [1, 3, 5], 3));
		self.assertEqual(-1, chop(6, [1, 3, 5], 3));

		self.assertEqual(0,  chop(1, [1, 3, 5, 7], 4));
		self.assertEqual(1,  chop(3, [1, 3, 5, 7], 4));
		self.assertEqual(2,  chop(5, [1, 3, 5, 7], 4));
		self.assertEqual(3,  chop(7, [1, 3, 5, 7], 4));
		self.assertEqual(-1, chop(0, [1, 3, 5, 7], 4));
		self.assertEqual(-1, chop(2, [1, 3, 5, 7], 4));
		self.assertEqual(-1, chop(4, [1, 3, 5, 7], 4));
		self.assertEqual(-1, chop(6, [1, 3, 5, 7], 4));
		self.assertEqual(-1, chop(8, [1, 3, 5, 7], 4));

#--------------------------------------------------- main
if __name__ == "__main__":
	unittest.main()	

